<template>
  <el-dialog v-model="open" title="报告模板管理" width="500px" append-to-body @open="initOpen" @close="close" destroy-on-close>
    <el-form :model="form" ref="formRef" label-width="120px" :rules="rules" scroll-to-error>
      <el-form-item label="报告模板类型" prop="reportType">
        <el-select v-model="form.reportType" clearable style="width: 100%" @change="getInput" :disabled="!!form.id">
          <el-option v-for="item in reportTypeOptions" :key="item.dictId" :label="item.dictName"
            :value="item.dictId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地震输入方式" prop="input">
        <el-select v-model="form.input" clearable style="width: 100%" :disabled="!!form.id">
          <el-option v-for="item in inputOptions" :key="item.dictItemId" :label="item.dictItemName"
            :value="item.dictItemId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模板编号" prop="num">
        <el-input v-model="form.num" clearable :disabled="!!form.id"></el-input>
      </el-form-item>
      <el-form-item label="模板名称" prop="name">
        <el-input v-model="form.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="模板说明" prop="templateDesc">
        <el-input v-model="form.templateDesc" clearable type="textarea" :autosize="{ minRows: 3, maxRows: 6 }"
          resize="none"></el-input>
      </el-form-item>
      <el-form-item label="模板文件" prop="attachId" v-if="!form.id">
        <FileUpload v-model="form.file" ref="uploadRef" :limit="1" :fileType="['doc', 'docx']" :isShowTip="true"
          @uploadSuccess="uploadSuccess" />
      </el-form-item>
      <!-- <el-form-item label="创建人" prop="createUser">
        <span>{{ form.createUserName }}</span>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <span>{{ form.createTime }}</span>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button type="primary" @click="save" auto-insert-space>保存</el-button>
      <el-button plain @click="close" auto-insert-space>取消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getTemplateNum, addTempalte, getDetail, getInputOptions, getReportTypeOptions, getByTemplateNum, getByTemplateName } from '@/api/searchExport/report/templateManage'

const props = defineProps({
  open: Boolean,
  id: String
})
const emits = defineEmits(['update:open', 'save', 'update:id'])
const { proxy } = getCurrentInstance()

const initForm = () => ({})
const form = ref(initForm())
const numRepeat = (rule, value, cb) => {
  if (form.value.id) return cb()
  if (value) {
    getByTemplateNum({ num: value }).then(res => {
      if (res.code == 200) {
        if (res.data) {
          cb(new Error(res.data))
        } else {
          cb()
        }
      }
    })
  } else {
    cb()
  }
}
const nameRepeat = (rule, value, cb) => {
  if (value) {
    let { id, num } = form.value
    let data = id ? { num, name: value } : { name: value }
    getByTemplateName(data).then(res => {
      if (res.code == 200) {
        if (res.data) {
          cb(new Error(res.data))
        } else {
          cb()
        }
      }
    })
  } else {
    cb()
  }
}
const rules = {
  reportType: [{ required: true, message: '请选择报告模板类型', trigger: 'change' }],
  input: [{ required: true, message: '请选择地震输入方式', trigger: 'change' }],
  num: [
    { required: true, message: '请填写模板编号', trigger: 'blur' },
    { validator: numRepeat, trigger: 'change' }
  ],
  name: [
    { required: true, message: '请填写模板名称', trigger: 'blur' },
    { validator: nameRepeat, trigger: 'blur' }
  ],
  attachId: [{ required: true, message: '请选择模板文件', trigger: 'change' }],
  createUser: [{ required: true, message: '请填写创建人', trigger: 'blur' }],
  createTime: [{ required: true, message: '请填写创建时间', trigger: 'blur' }]
}


const reportTypeOptions = ref([])
const getReportType = async () => {
  let res = await getReportTypeOptions({ dictDirId: 'fxqhpg_temp' })
  if (res.code == 200) {
    // reportTypeOptions.value = res.data
    res.data.map(item => {
      if(!reportTypeOptions.value.find(val => val.dictId == item.dictId)){
        reportTypeOptions.value.push(item)
      }
    })
    console.log(reportTypeOptions)
  }
}
const inputOptions = ref([])
const getInput = (dictId) => {
  inputOptions.value = []
  form.value.input = ''
  getInputOptions({ dictId }).then(res => {
    if (res.code == 200) {
      inputOptions.value = res.data
    }
  })
}

const initOpen = () => {
  getReportType()
  if (props.id) {
    getFormDetail(props.id)
  }
}

const getCode = () => {
  const { id, reportType, input } = form.value
  if (!id) {
    getTemplateNum({ reportType, input }).then(res => {
      form.value.num = res.data
    })
  }
}

watch([() => form.value.reportType, () => form.value.input], () => {
  if (form.value.reportType && form.value.input) {
    getCode()
  }
})

const uploadSuccess = (file) => {
  form.value.file = file
  form.value.attachId = file[0].attachId
  proxy.$refs.formRef.clearValidate('attachId')
}

const save = () => {
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      const { id, attachId, name, templateDesc } = form.value
      let msg = id ? '修改成功！' : '保存成功！'
      let data = id ? { id, attachId: '', name, templateDesc } : form.value
      addTempalte(data).then(res => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess(msg)
          close()
          emits('save')
        }
      })
    }
  })
}

const close = () => {
  proxy.resetAllForm(form.value, initForm())
  proxy.resetForm('formRef')
  emits('update:open', false)
  emits('update:id', '')
}

const getFormDetail = (id) => {
  getDetail({ id }).then(res => {
    if (res.code == 200) {
      form.value = res.data
      getInputOptions({ dictId: form.value.reportType }).then(result => {
        if (result.code == 200) {
          inputOptions.value = result.data
          form.value.input = res.data.input
        }
      })
    }
  })
}
</script>
<style scoped>
.el-form {
  padding-top: 20px;
}
</style>